package view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.example.administrator.text.R;
import java.util.ArrayList;
import java.util.List;
import adapter.ViewPagerHome;
import entity.HomeZhuYe;
import util.HomeUtil;
import util.LogUtil;

/**
 * 头部组合控件
 */
public class CustomViewPager extends FrameLayout{
    public static final int MSG_UPDATE_IMAGE  = 1;               //请求更新显示的View。
    public static final int MSG_KEEP_SILENT   = 2;              //请求暂停轮播。
    private boolean mStart;                                    //判断是否轮播
    private static int mVPSpeed = 4*1000;                     //头部ViewPager图片跳转的速度给两个默认时间
    private List<ImageView> mListIv = new ArrayList<>();     //放头部ViewPager 中的小图片
    private int mCount;                                     //辅助上面属性
    private int mPosition;                                 //头部ViewPager用的第三方的 返回的positiuon不正确，mPosition为了得到正确的positiuon
    private static int mCurrentIndex = 0;                 // 记录当前选中位置
    private boolean mSlide;                              //判断ViewPager是否滑动
    private Context mContext;
    private LoopViewPager mLoopViewPager;
    private LinearLayout mLinearLayout;              //导航控件
    private FragmentManager mFragmentManager;
    private ViewPagerHome mViewPagerHome;
    private boolean mWhether = false;             //是否循环

    private Handler mHandler = new Handler(){
        @Override public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(mHandler.hasMessages(MSG_UPDATE_IMAGE)){
                mHandler.removeMessages(MSG_UPDATE_IMAGE);
            }
            super.handleMessage(msg);
            switch (msg.what){
                case MSG_UPDATE_IMAGE:
                    if(mWhether) {
                        if (mStart) {
                            mLoopViewPager.setCurrentItem(mLoopViewPager.getCurrentItem() + 1);
                            mHandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, mVPSpeed);
                        }
                    }
                    break;
                case MSG_KEEP_SILENT:
                    mStart = false;
                    //只要不发送消息就暂停了
                    break;
            }
        }
    };

    public CustomViewPager(Context context) {
        super(context);

    }

    public CustomViewPager(Context context,AttributeSet attrs){
        super(context, attrs);
        this.mContext = context;
        init();
    }

    /**
     * 不需要时,可以调用此方法来关闭资源
     *
     */
    public void getOnDestroy(){

        if(mHandler !=null){mHandler.removeCallbacksAndMessages(null);}

        if(mListIv !=null){mListIv.clear();}

        if(mViewPagerHome !=null){mViewPagerHome.getRemoveFM();}

    }

    /**
     * 如果不调用就不轮播
     * @param whewther true需要跳动
     */
    public void setWhewther(boolean whewther){
        this.mWhether = whewther;
    }

    /**
     * 必须要传入的参数
     */
    public void setFragmentManager(FragmentManager fm){
        this.mFragmentManager = fm;
    }

    /**
     *传入数据 用于显示UI
     */
    public void loadDatas(List<HomeZhuYe.BannerModelsBean.TextModelsBean> list, List<HomeZhuYe.BannerModelsBean.PicModelsBean> imagelist){
        final List<HomeZhuYe.BannerModelsBean.TextModelsBean> mListString = list;
        final List<HomeZhuYe.BannerModelsBean.PicModelsBean> mListImage = imagelist;

        if (mListString != null && mListImage != null && mListImage.size() !=0) {
            mViewPagerHome = new ViewPagerHome(
                    mFragmentManager,mListString,mListImage);
            mLoopViewPager.setAdapter(mViewPagerHome);
            mLoopViewPager.setCurrentItem(mListImage.size());//设置为第一张
            if (mListString.size()>0) {

                if(mWhether){
                    mStart = true;//开启轮播
                    mHandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, mVPSpeed);
                }
                //下方小图标
                HomeUtil.getHemeUtilNew().getViewPagerCircularDot(mContext, R.drawable.home_viewpager, false, true, mListImage, mListIv, mLinearLayout);
                mListIv.get(0).setSelected(true);
            } else {
                if (mListImage.size() >= 1) {

                    if(mWhether){
                        mStart = true;
                        mHandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, mVPSpeed);
                    }
                    HomeUtil.getHemeUtilNew().getViewPagerCircularDot(mContext, R.drawable.home_viewpager, false, false, mListImage, mListIv, mLinearLayout);
                    mListIv.get(0).setSelected(true);
                }
            }

            mLoopViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
                @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                }

                @Override public void onPageSelected(int position) {
                    if (mListImage.size() > 0) {
                        if (mListString.size()>0) {
                            mCount = mListImage.size() + 1;
                        } else {
                            mCount = mListImage.size();
                        }

                        mPosition = position - 1;
                        if (mPosition < 0) {
                            mPosition += mCount;
                        } else {
                            mPosition = position % mCount;
                        }
                        mListIv.get(0).setSelected(false);//防止错乱
                        if(mCurrentIndex < mListIv.size()){
                            mListIv.get(mCurrentIndex).setSelected(false);
                        }
                        mCurrentIndex = mPosition;
                        LogUtil.eE("Position", "      " + mPosition);
                        if(mPosition < mListIv.size()){
                            mListIv.get(mPosition).setSelected(true);
                        }
                    }

                }

                @Override public void onPageScrollStateChanged(int state) {}});

            mLoopViewPager.setOnTouchListener(new OnTouchListener() {
                @Override public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN://手指刚接触
                            mSlide = true;
                            mHandler.sendEmptyMessage(MSG_KEEP_SILENT);
                            break;
                        case MotionEvent.ACTION_UP://离开屏幕
                            mHandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, mVPSpeed);
                            mSlide = false;
                            mStart = true;
                            break;
                        case MotionEvent.ACTION_CANCEL:
                            mHandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, mVPSpeed);
                            mSlide = false;
                            mStart = true;
                            break;
                    }
                    return false;
                }
            });
        }

    }

    private void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.custem_headview, this, true);
        mLoopViewPager = (LoopViewPager) this.findViewById(R.id.vp_head);
        mLinearLayout = (LinearLayout) this.findViewById(R.id.linear_home);
    }

}
